package com.hundsun.cprs.yyt.util;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


/**
 * 订单等编码生成器
 * 
 * @author linbo
 * @version $Id: IdCounter.java,v 1.1.1.1-RC1 2017年10月24日 Exp $
 */
@Service("orderNoCreator")
public class OrderNoCreator {
	@Autowired
	private RedisSequenceFactory mRedisSequenceFactory;
	@Autowired
	RedisTemplate<String, Serializable> redisTemplate;

	private long baseCounter = 1000000L;
	private String defaultKey = "defaultCounter";

	/**
	 * 生成订单编码
	 * 
	 * @param counterKey
	 *            计数器key
	 * @param typeFour
	 *            4位业务编码，如0503:提货手续费业务码
	 * @return
	 */
	public String createNo(String counterKey, String typeFour) {
		long original = 0L;

		// 获取 code 值
		original = mRedisSequenceFactory.generate(counterKey, this.getTodayEndTime());

		// 第一次，设置初始值
		if (original == 0L) {
			mRedisSequenceFactory.set(counterKey, 1, this.getTodayEndTime());
		}
		// 获得加1后的值
		long currentId = original;
		String ssTimeStr = DateUtil.getDateTime("yyyyMMddHHmmss", new Date());
		StringBuilder sb = new StringBuilder();
		sb.append(ssTimeStr);
		sb.append(typeFour);
		sb.append((baseCounter + currentId));
		return sb.toString();

	}

	/**
	 * 生成订单编码
	 * 
	 * @param typeFour
	 *            4位业务编码，如0503:提货手续费业务码
	 * @return
	 */
	public String createNo(String typeFour) {
		long original = 0L;

		// 获取 code 值
		original = mRedisSequenceFactory.generate(defaultKey, this.getTodayEndTime());

		// 第一次，设置初始值
		if (original == 0L) {
			mRedisSequenceFactory.set(defaultKey, 0, this.getTodayEndTime());
		}
		// 获得加1后的值
		long currentId = original;
		String ssTimeStr = DateUtil.getDateTime("yyyyMMddHHmmss", new Date());
		StringBuilder sb = new StringBuilder();
		sb.append(ssTimeStr);
		sb.append(typeFour);
		sb.append((baseCounter + currentId));
		return sb.toString();

	}
	
	/**
	 * 自增计数编码
	 * 
	 * @param counterKey key
	 *            4位业务编码，如0503:提货手续费业务码
	 * @return
	 */
	public String createAIOnly(String counterKey) {
		long original = 0L;

		// 获取 code 值
		original = mRedisSequenceFactory.generate(counterKey);

		long currentId = original;
		StringBuilder sb = new StringBuilder();
		sb.append((baseCounter + currentId));
		return sb.toString();

	}

	/**
	 * 当日结束时间
	 * 
	 * @return
	 */
	private static Date getTodayEndTime() {
		Calendar todayEnd = Calendar.getInstance();
		todayEnd.set(Calendar.HOUR_OF_DAY, 23);
		todayEnd.set(Calendar.MINUTE, 59);
		todayEnd.set(Calendar.SECOND, 59);
		todayEnd.set(Calendar.MILLISECOND, 999);
		return todayEnd.getTime();
	}

}
